import {
  ExecutionContext,
  Injectable,
  Logger,
  UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  private readonly logger = new Logger(JwtAuthGuard.name);

  canActivate(context: ExecutionContext) {
    // 添加日志
    this.logger.debug(`JWT Auth Guard: Checking authentication`);

    // 获取请求对象
    const request = context.switchToHttp().getRequest();
    this.logger.debug(
      `Request authorization header: ${request.headers.authorization}`,
    );

    // 调用父类的canActivate方法
    return super.canActivate(context);
  }

  handleRequest(err: any, user: any, info: any) {
    // 添加日志以便于调试
    this.logger.debug(`JWT Auth Guard: Handling request`);

    if (info) {
      this.logger.error(`JWT Auth Error: ${JSON.stringify(info)}`);
    }

    // 如果有错误或者没有用户信息，抛出未授权异常
    if (err || !user) {
      const errorMsg = err?.message || 'User not found';
      this.logger.error(`Authentication failed: ${errorMsg}`);
      throw err || new UnauthorizedException('未授权访问');
    }

    // 记录用户信息
    this.logger.debug(`Authenticated user: ${JSON.stringify(user)}`);
    return user;
  }
}
